package com.tianji.learning.service.impl;

import com.tianji.api.client.ai.AIClient;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.service.AIService;
import com.tianji.learning.service.IInteractionReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @version: 1.0
 * @Author: ljy
 * @description:
 * @date: 2025-09-05 16:39
 */
@Service
public class AIServiceImpl implements AIService {
    @Autowired
    private AIClient aiClient;

    @Autowired
    private IInteractionReplyService interactionReplyService;

    /**
     * AI自动回复
     */
    @Async //异步处理
    @Override
    public void autoReply(InteractionQuestion interactionQuestion) {
        String question = String.format("""
                请从专业角度回答用户提问：
                1. 提问的标题是：%s
                2. 提问的问题描述是：%s
                """, interactionQuestion.getTitle(), interactionQuestion.getDescription());

        UserContext.setUser(interactionQuestion.getUserId());//设置用户ID，否则feign调用出现401

        String reply = aiClient.chatText(question);

        ReplyDTO replyDTO = ReplyDTO.builder()
                .userId(9999L)//代表AI身份的用户，非正常用户
                .questionId(interactionQuestion.getId())//原问题ID
                .content(reply)//AI回复的答案
                .isStudent(false)//非学员回答
                .anonymity(false)//是否匿名提问
                .build();

        interactionReplyService.saveReply(replyDTO);
    }
}
